﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.Core;
using System.Collections.Specialized;
using System.Web;

namespace Yuanlin.Business
{
    public class CompanySearchResult : YuanlinUserControl
    {
        private NameValueCollection formData;
        protected ValuedTextBox greenNumSearchTextBox;
        protected ValuedTextBox mobilePhoneSearchTextBox;
        protected ValuedDropDownList provinceDropDownList;
        protected ValuedDropDownList cityDropDownList;
        protected ValuedDropDownList townDropDownList;
        protected ValuedDropDownList smallTownDropDownList;
        protected ValuedDropDownList companyTypeDropDownList;
        protected Repeater list;
        protected Pager pager;
        protected Button searchCompanyButton;
        protected CurrentPage currentPage;
        private int provinceId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.ProvinceId);
        private int cityId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.CityId);
        private int townId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.TownId);
        private int smallTownId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.SmallTownId);
        private string companyName = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.CompanyName);
        private int level = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.Level);
        private int area = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.Area);
        private string greenNum = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.GreenNum);
        private string mobilePhoneKey = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.MobilePhoneKey);
        private int companyType = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.CompanyType);

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack && !AjaxManager.IsCallBack)
            {
                Bind();
                BindCompanies();
            }
            searchCompanyButton.Click += new EventHandler(searchCompanyButton_Click);
            AjaxManager.Register(this, "Search");
        }
        protected void searchCompanyButton_Click(object sender, EventArgs e)
        {
            formData = HttpContext.Current.Request.Form;
            ReBindCompanies();
        }

        private void Bind()
        {
            greenNumSearchTextBox.Value = greenNum;
            mobilePhoneSearchTextBox.Value = mobilePhoneKey;

            EntityList companyTypes = BusinessManager.GetCompanyTypeList(RequestHelper.BuildGetCompanyTypeListRequest());

            CompanyType topCompanyType = new CompanyType();
            topCompanyType.Title.Value = "<请选择>";
            topCompanyType.EntityId.Value = -1;
            companyTypes.Insert(0, topCompanyType);

            this.companyTypeDropDownList.DataSource = companyTypes;
            this.companyTypeDropDownList.DataValueField = "EntityId";
            this.companyTypeDropDownList.DataTextField = "Title";
            this.companyTypeDropDownList.DataBind();
            this.companyTypeDropDownList.Value = companyType.ToString();

            AreaListRequest request = new AreaListRequest();
            request.UpAreaId = 0;
            EntityList topCategories = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request));
            EntityList defaultCategories1 = new EntityList()  ;
            EntityList defaultCategories2 = new EntityList()  ;
            EntityList defaultCategories3 = new EntityList()  ;

            Area topCategory = new Area();
            topCategory.Title.Value = "<选择省>";
            topCategory.EntityId.Value = -1;

            Area topCategory1 = new Area();
            topCategory1.Title.Value = "<选择市>";
            topCategory1.EntityId.Value = -1;

            Area topCategory2 = new Area();
            topCategory2.Title.Value = "<选择县>";
            topCategory2.EntityId.Value = -1;

            Area topCategory3 = new Area();
            topCategory3.Title.Value = "<选择乡>";
            topCategory3.EntityId.Value = -1;

            if (provinceId > 0)
            {
                request = new AreaListRequest();
                request.UpAreaId = provinceId;
                defaultCategories1 = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request));
            }
            if (cityId > 0)
            {
                request = new AreaListRequest();
                request.UpAreaId = cityId;
                defaultCategories2 = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request));
            }
            if (townId > 0)
            {
                request = new AreaListRequest();
                request.UpAreaId = townId;
                defaultCategories3 = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request));
            }

            topCategories.Insert(0, topCategory);
            defaultCategories1.Insert(0, topCategory1);
            defaultCategories2.Insert(0, topCategory2);
            defaultCategories3.Insert(0, topCategory3);

            this.provinceDropDownList.DataSource = topCategories;
            this.provinceDropDownList.DataValueField = "EntityId";
            this.provinceDropDownList.DataTextField = "Title";
            this.provinceDropDownList.DataBind();
            this.provinceDropDownList.Value = provinceId.ToString();

            this.cityDropDownList.DataSource = defaultCategories1;
            this.cityDropDownList.DataValueField = "EntityId";
            this.cityDropDownList.DataTextField = "Title";
            this.cityDropDownList.DataBind();
            this.cityDropDownList.Value = cityId.ToString();

            this.townDropDownList.DataSource = defaultCategories2;
            this.townDropDownList.DataValueField = "EntityId";
            this.townDropDownList.DataTextField = "Title";
            this.townDropDownList.DataBind();
            this.townDropDownList.Value = townId.ToString();

            this.smallTownDropDownList.DataSource = defaultCategories3;
            this.smallTownDropDownList.DataValueField = "EntityId";
            this.smallTownDropDownList.DataTextField = "Title";
            this.smallTownDropDownList.DataBind();
            this.smallTownDropDownList.Value = smallTownId.ToString();
        }
        private void BindCompanies()
        {
            EntityList users = new EntityList();

            YuanlinUserListRequest request = new YuanlinUserListRequest();

            if (!string.IsNullOrEmpty(greenNum))
            {
                Member member = MemberManager.GetMember(greenNum);
                if (member != null)
                {
                    request.MemberId = member.MemberId;
                }
                else
                {
                    request.MemberId = Guid.NewGuid();//绿商号只能全字匹配，找不到就新生成一个
                }
            }
            if (!string.IsNullOrEmpty(companyName))
            {
                request.CompanyName = System.Web.HttpUtility.HtmlEncode(companyName);
            }
            else
            {
                request.CompanyName = "";
            }
            request.AreaId = area;
            request.AreaLevel = level;
            request.MobilePhoneKey = mobilePhoneKey;
            request.ProvinceId = provinceId;
            request.CityId =cityId;
            request.TownId = townId;
            request.SmallTownId = smallTownId;
            if (companyType > -1)
            {
                request.CompanyType = companyType.ToString();
            }
            else
            {
                request.CompanyType = "";
            }
            EntityList userList = BusinessManager.GetYuanlinUserList(RequestHelper.BuildGetUserListRequest(request));
            if (userList.Count > 0)
            {
                YuanlinUser user = userList[0] as YuanlinUser;
                if (user != null)
                {
                    users.Add(user);
                }
            }

            list.DataSource = RemoveAdminUser(users);
            list.DataBind();

            if (pager != null && currentPage != null)
            {
                pager.TotalPages = pager.CalculateTotalPages(users.Count);
                currentPage.TotalRecords = users.Count;
                currentPage.TotalPages = pager.TotalPages;
                currentPage.PageIndex = pager.PageIndex;
            }
        }
        private EntityList RemoveAdminUser(EntityList users)
        {
            EntityList filterUsers = new EntityList();
            foreach (User user in users)
            {
                if (user.EntityId.Value != 10000)
                {
                    filterUsers.Add(user);
                }
            }
            return filterUsers;
        }
        private void ReBindCompanies()
        {
            int provinceID = 0;
            int cityID = 0;
            int townID = 0;
            int smallTownID = 0;
            int companyType = 0;
            string companyNameStr = companyName == "-1" ? "" : companyName;
            string greenNumStr = string.Empty;
            string mobilePhoneKey = string.Empty;
            int areaID = 0;
            int level = 0;

            if (!string.IsNullOrEmpty(formData[provinceDropDownList.UniqueID]))
            {
                provinceID = int.Parse(formData[provinceDropDownList.UniqueID]);
            }
            if (!string.IsNullOrEmpty(formData[cityDropDownList.UniqueID]))
            {
                cityID = int.Parse(formData[cityDropDownList.UniqueID]);
            }
            if (!string.IsNullOrEmpty(formData[townDropDownList.UniqueID]))
            {
                townID = int.Parse(formData[townDropDownList.UniqueID]);
            }
            if (!string.IsNullOrEmpty(formData[smallTownDropDownList.UniqueID]))
            {
                smallTownID = int.Parse(formData[smallTownDropDownList.UniqueID]);
            }

            if (smallTownID > 0)
            {
                areaID = smallTownID;
                level = 4;
            }
            else if (townID > 0)
            {
                areaID = townID;
                level = 3;
            }
            else if (cityID > 0)
            {
                areaID = cityID;
                level = 2;
            }
            else if (provinceID > 0)
            {
                areaID = provinceID;
                level = 1;
            }

            if (!string.IsNullOrEmpty(formData[this.companyTypeDropDownList.UniqueID]))
            {
                companyType = int.Parse(formData[this.companyTypeDropDownList.UniqueID]);
            }

            if (!string.IsNullOrEmpty(formData[this.greenNumSearchTextBox.UniqueID]))
            {
                greenNumStr = formData[this.greenNumSearchTextBox.UniqueID];
            }

            if (!string.IsNullOrEmpty(formData[this.mobilePhoneSearchTextBox.UniqueID]))
            {
                mobilePhoneKey = formData[this.mobilePhoneSearchTextBox.UniqueID];
            }

            HttpContext.Current.Response.Redirect(SiteUrls.Instance().GetCompanySearchResultUrl(areaID, level, companyType, System.Web.HttpUtility.HtmlEncode(companyNameStr), System.Web.HttpUtility.HtmlEncode(greenNumStr), System.Web.HttpUtility.HtmlEncode(mobilePhoneKey), provinceID, cityID, townID, smallTownID));

        }

        [AjaxMethod(IncludeControlValuesWithCallBack = false)]
        public string GetChildCategories(int parentCategoryID)
        {
            if (parentCategoryID == -1)
            {
                return string.Empty;
            }
            AreaListRequest request = new AreaListRequest();
            request.UpAreaId = parentCategoryID;
            EntityList categories = BusinessManager.GetAreaList(RequestHelper.BuildGetAreaListRequest(request));

            if (categories != null && categories.Count > 0)
            {
                string categoryFormat = "{0}:{1}";
                string categoryString = string.Empty;
                foreach (Area category in categories)
                {
                    if (categoryString != string.Empty)
                    {
                        categoryString += ";";
                    }
                    categoryString += string.Format(categoryFormat, category.EntityId.Value.ToString(), category.Title.Value);
                }
                return categoryString;
            }

            return string.Empty;
        }

        public string GetCompanyTypeTitles(string companyTypeIds)
        {
            string returnValue = string.Empty;
            if (companyTypeIds.Length > 0)
            {
                CompanyType companyType = null;
                string[] array = companyTypeIds.Trim(',').Split(',');
                foreach (string str in array)
                {
                    companyType = BusinessManager.GetCompanyType(Globals.ChangeType<int>(str));
                    if (companyType != null)
                    {
                        returnValue += "," + companyType.Title;
                    }
                }
            }
            return returnValue.Trim(',');
        }
    }
}